﻿using System;
using K9Nano.Updater.Pipes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace K9Nano.Updater;

public class DefaultUpdateManager : IUpdateManager
{
    protected readonly IServiceProvider ServiceProvider;

    public DefaultUpdateManager(IServiceProvider serviceProvider)
    {
        ServiceProvider = serviceProvider;
    }

    public async Task<AvailableVersion?> GetAvailableVersionAsync(CancellationToken cancellation = default)
    {
        var logger = ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger(nameof(DefaultUpdateManager));
        var currentVersion = new Version(ServiceProvider.GetRequiredService<IOptions<UpdaterOptions>>().Value.Version);
        logger.LogInformation("当前版本为：{current}", currentVersion);
        var client = ServiceProvider.GetRequiredService<IUpdateClient>();
        var result = await client.GetLatestVersionAsync(cancellation);
        logger.LogInformation("最新版本为：{latest}", result?.Version);
        if (result is null || result.Version <= currentVersion)
        {
            return null;
        }
        return result;
    }


    public async Task<bool> TryUpdateAsync(Action<double> progressReporter, CancellationToken cancellation = default)
    {
        var updatePipeManger = ServiceProvider.GetRequiredService<IUpdatePipeManger>();
        var context = new UpdateContext(ServiceProvider, progressReporter);
        await updatePipeManger.InvokeAsync(context, cancellation);
        return context.Success;
    }
}
